using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using Flaschengeist;
using Flaschengeist.DataAccess;
using Flaschengeist.Entities;
using Flaschengeist.Views;
using UnityEngine;

namespace Flaschengeist.Processes 
{
	public class LoadScore : MonoBehaviour
	{
		private XmlRpc xmlrpc;
		private ErrorView errorView;
		private int scoreLimit = 10;
		
		public void Start()
		{						
			errorView = gameObject.GetComponent<ErrorView>();
			xmlrpc = gameObject.AddComponent<XmlRpc>();
			xmlrpc.Completed += LoadCompleted;
		}
		
		private void LoadCompleted(string xml)
		{
			var score = new List<ScoreItem>();
			
			foreach (XmlNode item in xml.GetRecords())
			{
				var scoreItem = new ScoreItem();								
				foreach (XmlNode node in item.ChildNodes) 
				{
					if (node.HasChildNodes)
					{
						if(node.FirstChild.InnerText == "Name")
							scoreItem.PlayerName = node.LastChild.GetValueFromNode();	
														
						if(node.FirstChild.InnerText == "Score")
							scoreItem.Score = Int64.Parse(node.LastChild.GetValueFromNode());								
					}				
				}									
				score.Add(scoreItem);
			}
			Completed(score);
		}
		
		public void Process()
		{		
			try 
			{
				Debug.Log("Start load Score");
				var ht = new Hashtable();
				ht.Add("limit", scoreLimit);
				xmlrpc.Process("getScore", ht);
			} 
			catch (Exception ex) 
			{
				errorView.Show(ex);
			}
		}
					
		public event Action<IEnumerable<ScoreItem>> Completed;
	}
}

